#pragma once
#include "Comm.hpp"
// #include <iostream>
// #include <sys/types.h>
// #include <sys/stat.h>
// #include <unistd.h>

// 创建命名管道
class Init
{
public:
    Init()
    {
        umask(0);
        int n = ::mkfifo(gpipeFile.c_str(), gmode);
        if (n < 0) // 创建失败
        {
            std::cerr << "mkfifo error" << std::endl;
            return;
        }
        std::cout << "mkfifo success" << std::endl;
    }
    ~Init()
    {
        // 删除命名管道
        int n = ::unlink(gpipeFile.c_str());
        if (n < 0)
        {
            std::cerr << "unlink error" << std::endl;
            return;
        }
        std::cout << "unlink sucess" << std::endl;
    }

private:
};

Init it;

class Server
{
public:
    Server():_fd(gdefaultfd)
    {}

    //读端打开管道
    bool OpenPipeRead()
    {
        _fd = OpenPipe(gForRead);
        if(_fd < 0) return false;
        return true;
    }

    //读取信息
    //输出型参数
    int RecvPipe(std::string *out)
    {
        char buffer[gsize];
        ssize_t n = ::read (_fd, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }

    //关闭管道
    void ClosePipe()
    {
        ClosePipeHelper(_fd);
    }

    ~Server()
    {}

private:
    int _fd;
};

